//
//  UrbanPhotoViewController.m
//  UrbanManagement
//
//  Created by Can on 18/4/11.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "UrbanPhotoViewController.h"
#import "NSString+StringSize.h"

@interface UrbanPhotoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UIView *backgroundView;

@end

@implementation UrbanPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    
    [self initTitleWithTitle:@"现场照片"];
    
    _imageArr = [NSMutableArray new];
    
    [self creatView];
    
    [self getImages];
}

- (void)getImages
{
    [HudHelper showProgressHudWithMessage:@"正在加载图片" toView:self.view];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if (self->_imageOne.length > 1) {
            NSString *imgUrl = [self->_imageOne  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            UIImage *newImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgUrl];//用地址去本地找图片
            if (newImage != nil) {//如果本地有
                // newImage就是图片
                [self->_imageArr addObject:newImage];
            }else{
                //下载图片
                [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imgUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                    //这里是处理下载进度的,好像没必要管他
                } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                    if (image) {//下载完成后
                        //同上处理
                        [self->_imageArr addObject:image];
                        [self getimgTow];
                    }
                }];
            }
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper hideHudToView:self.view];
                [self->_collectionView reloadData];
            });
        }
    });
}

- (void)getimgTow
{
    if (_imageTwo.length > 1) {
        NSString *imgUrl = [self->_imageTwo  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        UIImage *newImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgUrl];//用地址去本地找图片
        if (newImage != nil) {//如果本地有
            // newImage就是图片
            [self->_imageArr addObject:newImage];
        }else{
            //下载图片
            [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:imgUrl] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                //这里是处理下载进度的,好像没必要管他
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                if (image) {//下载完成后
                    //同上处理
                    [self->_imageArr addObject:image];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [HudHelper hideHudToView:self.view];
                        [self->_collectionView reloadData];
                    });
                }
            }];
        }
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [HudHelper hideHudToView:self.view];
            [self->_collectionView reloadData];
        });
    }
}

- (void)creatView{
    CGFloat height = NavBarHeight;
    //创建一个layout布局类
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //设置布局方向为垂直流布局
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //创建collectionView 通过一个布局策略layout来创建
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 141*screenW_6) collectionViewLayout:layout];
    _collectionView.center = CGPointMake(self.view.center.x, self.view.center.y - height);
    _collectionView.backgroundColor = [UIColor blackColor];
    //代理设置
    _collectionView.delegate=self;
    _collectionView.dataSource=self;
    _collectionView.scrollEnabled = NO;
    //注册item类型 这里使用系统的类型
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
    
    [self.view addSubview:_collectionView];
}

//返回分区个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

//返回每个分区的item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _imageArr.count;
}

//返回每个item
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREENW/2 - 5, 141*screenW_6)];
    
    imageView.backgroundColor = [UIColor whiteColor];
    
    imageView.image = _imageArr[indexPath.row];
    
    [imageView setContentMode:UIViewContentModeScaleAspectFill];
    
    imageView.clipsToBounds = YES;
    
    [cell addSubview:imageView];
    
    return cell;
}

//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(SCREENW/2 - 5, 141*screenW_6);
}


#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self cleckImageViewAction:indexPath.row];
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//点击图片后的方法(即图片的放大全屏效果)
- (void) cleckImageViewAction:(NSInteger)num{
    //创建一个黑色背景
    _backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];

    [_backgroundView setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:_backgroundView];

    CGFloat height = NavBarHeight;
    //创建显示图像的视图
    //初始化要显示的图片内容的imageView
    UIImageView *browseImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH - height)];
    browseImgView.contentMode = UIViewContentModeScaleAspectFit;
    
    //要显示的图片，即要放大的图片
    browseImgView.image = _imageArr[num];
    
    [_backgroundView addSubview:browseImgView];
    
    browseImgView.userInteractionEnabled = YES;
    //添加点击手势（即点击图片后退出全屏）
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
    [browseImgView addGestureRecognizer:tapGesture];
    
    [self shakeToShow:_backgroundView];//放大过程中的动画
}

-(void)closeView{
    [_backgroundView removeFromSuperview];
}

//放大过程中出现的缓慢动画
- (void) shakeToShow:(UIView*)aView{
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.3;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
